<template>
  <div class="profile-container">
    <el-card>
      <div slot="header">
        <h3>个人信息</h3>
      </div>
      
      <el-button v-if="!userProfile" type="primary" @click="checkAuthStatus">检查认证状态</el-button>
      
      <div v-if="!userProfile" class="debug-tools">
        <h4>调试工具</h4>
        <el-row :gutter="10">
          <el-col :span="8">
            <el-button type="primary" size="small" @click="testAuth">测试认证</el-button>
          </el-col>
          <el-col :span="8">
            <el-button type="warning" size="small" @click="refreshToken">刷新登录状态</el-button>
          </el-col>
          <el-col :span="8">
            <el-button type="danger" size="small" @click="logout">退出重新登录</el-button>
          </el-col>
        </el-row>
      </div>
      
      <el-form v-if="userProfile" :model="userProfile" ref="profileForm" label-width="100px" :rules="rules">
        <el-form-item label="用户名/学号">
          <el-input v-model="userProfile.username" disabled></el-input>
        </el-form-item>
        
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userProfile.name"></el-input>
        </el-form-item>
        
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="userProfile.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="userProfile.phone"></el-input>
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userProfile.email"></el-input>
        </el-form-item>
        
        <el-form-item label="角色">
          <el-tag v-if="userProfile.role === 'STUDENT'" type="success">学生</el-tag>
          <el-tag v-else-if="userProfile.role === 'TEACHER'" type="warning">导师</el-tag>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="saveProfile" :loading="loading">保存</el-button>
          <el-button type="default" @click="fetchUserProfile">刷新</el-button>
        </el-form-item>
      </el-form>
      
      <div v-else class="loading-container">
        <el-skeleton :rows="6" animated />
      </div>
    </el-card>
  </div>
</template>

<script>
import request from '@/utils/request'
import { mapActions, mapGetters } from 'vuex'

export default {
  name: 'Profile',
  data() {
    return {
      userProfile: null,
      loading: false,
      rules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
        phone: [
          { required: true, message: '请输入手机号码', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters(['token'])
  },
  created() {
    console.log('Profile组件创建，当前token:', this.token)
    if (!this.token) {
      this.$message.error('您尚未登录，即将跳转到登录页面')
      this.$router.push('/login')
      return
    }
    this.fetchUserProfile()
  },
  methods: {
    ...mapActions(['updateUserInfo']),
    
    fetchUserProfile() {
      console.log('开始获取个人信息，当前token:', this.token)
      
      request({
        url: '/user/profile',
        method: 'get'
      }).then(response => {
        console.log('获取个人信息成功:', response)
        if (response.code === 200) {
          this.userProfile = response.data
        } else {
          this.$message.error(response.msg || '获取个人信息失败')
        }
      }).catch(error => {
        console.error('获取个人信息失败', error)
        this.$message.error('获取个人信息失败，请确保后端服务已启动 (错误: ' + (error.message || '未知错误') + ')')
      })
    },
    saveProfile() {
      this.$refs.profileForm.validate(valid => {
        if (valid) {
          this.loading = true
          console.log('开始保存个人信息:', this.userProfile)
          
          request({
            url: '/user/profile',
            method: 'put',
            data: this.userProfile
          }).then(response => {
            this.loading = false
            console.log('保存个人信息成功:', response)
            
            if (response.code === 200) {
              this.$message.success('个人信息更新成功')
              // 更新Vuex中的用户信息
              this.updateUserInfo({
                name: this.userProfile.name,
                gender: this.userProfile.gender,
                phone: this.userProfile.phone,
                email: this.userProfile.email
              })
            } else {
              this.$message.error(response.msg || '更新个人信息失败')
            }
          }).catch(error => {
            this.loading = false
            console.error('更新个人信息失败', error)
            this.$message.error('更新个人信息失败，请确保后端服务已启动 (错误: ' + (error.message || '未知错误') + ')')
          })
        }
      })
    },
    checkAuthStatus() {
      console.log('检查认证状态，当前token:', this.token)
      
      request({
        url: '/auth/status',
        method: 'get'
      }).then(response => {
        console.log('认证状态检查结果:', response)
        if (response.code === 200) {
          this.$alert(JSON.stringify(response.data, null, 2), '认证状态', {
            dangerouslyUseHTMLString: false
          });
        } else {
          this.$message.error(response.msg || '获取认证状态失败')
        }
      }).catch(error => {
        console.error('获取认证状态失败', error)
        this.$message.error('获取认证状态失败: ' + (error.message || '未知错误'))
      })
    },
    testAuth() {
      request({
        url: '/auth/info',
        method: 'get'
      }).then(response => {
        console.log('认证信息:', response)
        this.$message.success('认证成功，请查看控制台')
      }).catch(error => {
        console.error('认证失败', error)
        this.$message.error('认证失败: ' + (error.message || '未知错误'))
      })
    },
    refreshToken() {
      const token = this.token
      const username = JSON.parse(window.sessionStorage.getItem('userInfo') || '{}').username
      if (!username) {
        this.$message.error('未找到用户名，请先登录')
        this.$router.push('/login')
        return
      }
      
      this.$message.info('正在刷新登录状态...')
      this.fetchUserProfile()
    },
    logout() {
      this.$confirm('确定退出登录并返回登录页面?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('logout')
        this.$message.success('已退出登录')
        this.$router.push('/login')
      }).catch(() => {})
    }
  }
}
</script>

<style scoped>
.profile-container {
  padding: 20px;
}
.loading-container {
  margin: 20px 0;
}
.debug-tools {
  margin-bottom: 20px;
}
</style> 